<template>
  <!--  上传弹窗-->
  <el-dialog v-model="visible" :title="$t('oss.upload')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-upload :action="dataForm.url" :file-list="dataForm.fileList" drag multiple :before-upload="beforeUploadHandle"
      :on-success="successHandle" class="text-center">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text" v-html="$t('upload.text')"></div>
      <template v-slot:tip>
        <div class="el-upload__tip">{{ $t("upload.tip", { format: "pdf" }) }}一次只能上传一个文件</div>
      </template>
    </el-upload>
  </el-dialog>
</template>

<script lang="ts" setup>
import { defineComponent, reactive, ref } from "vue";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { ElMessage } from "element-plus";
// export default defineComponent({
// setup() {
//   return reactive({
const visible = ref(false);

const dataForm = reactive({
  num: 0,
  fileList: [] as any[],
  url: "",
  name: ""
});

const init = () => {
  visible.value = true;
  dataForm.fileList = [];
  dataForm.url = `${app.api}/oss/file/upload?access_token=${getToken()}`;
  dataForm.num = 0;
};
// 上传之前
const beforeUploadHandle = (file: IObject) => {
  console.log(file.type);
  if (file.type !== "application/pdf") {
    ElMessage.error("只支持pdf格式文件！");
    return false;
  }
  dataForm.num++;
};
const emit = defineEmits(["file", "fileList", "refreshDataList"]);
// 上传成功
const successHandle = (res: IObject, file: IObject, fileList: IObject[]) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  dataForm.url = res.data.url;
  emit("file", file);
  dataForm.fileList = fileList;
  emit("fileList", fileList);
  dataForm.num--;
  if (dataForm.num === 0) {
    ElMessage({
      message: "操作成功",
      type: "success",
      duration: 500,
      onClose: () => {
        visible.value = false;
        emit("refreshDataList");
      }
    });
  }
};

defineExpose({ init });
</script>
